import { ref, Ref, watchEffect } from "vue"
import { CtgyActions } from "@/store/actions"
import { ctgyGettersProxy } from "@/store/getters"
import { FirstCtgy, SecondCtgy } from "@/store/state"

// 1级分类到3级分类的所有业务处理
export default class FirstToThirdCtgy {
  static firstCtgyList: Ref<FirstCtgy[]> = ref([]) // 1级分类数据
  static firstCtgyActiveIndex: Ref<number> = ref(0) // 1级分类激活的tab索引
  static secondCtgyList: Ref<SecondCtgy[]> = ref([]) // 2级分类+3级分类

  // 获取所有1级分类
  static async getFirstCtgys() {
    await CtgyActions.findFirstCtgyList()
    FirstToThirdCtgy.firstCtgyList.value = ctgyGettersProxy.getFirstCtgyList
  }

  // 1级分类tab中的点击事件
  static changeTab(index: number) {
    FirstToThirdCtgy.firstCtgyActiveIndex.value = index
  }

  // 获取2级分类和对应的3级分类
  static getSecThrdCtgyList() {
    // 默认会自动执行一次并自动追踪响应式数据发生变化时,回调函数自动执行
    watchEffect(async () => {
      await CtgyActions.findSecThirdCtgyList(FirstToThirdCtgy.firstCtgyActiveIndex.value + 1)
      FirstToThirdCtgy.secondCtgyList.value = ctgyGettersProxy.getSecThirdCtgyList
    })
  }

  // 3级分类展开与收缩
  static openOrCollapse(event: Event, secondctgy: SecondCtgy) {
    const currentTarget = <HTMLBodyElement>event.currentTarget
    const ulPanel = currentTarget.parentElement! // 获取ul
    if (secondctgy.isReadyOpen) { // 当前最多显示5条3级分类
      if (secondctgy.thirdctgys.length % 3 === 0) {
        ulPanel.style.paddingBottom = 0.5 + 'rem'
      }
      secondctgy.isReadyOpen = false // 修改为false可以显示所有3级分类
    } else { // 当前显示所有3级分类
      if (secondctgy.thirdctgys.length % 3 === 0) {
        ulPanel.style.paddingBottom = '0'
      }
      secondctgy.isReadyOpen = true // 修改为true最多可以显示5条3级分类
    }
  }
}
